package com.echo.model.filter;

import com.alibaba.fastjson.JSONObject;
import com.echo.model.common.RequestHolder;
import com.echo.model.constant.CacheKey;
import com.echo.model.context.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author chen
 * @date 2018/8/29 15:29
 */
@Slf4j
@WebFilter
@Component
public class LoginFilter implements Filter {

    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/oauth/store", "/oauth/token", "/oauth/loginOut", "/user/login")));

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("过滤器初始化。");
    }

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String path = req.getServletPath();
        boolean allowedPath = ALLOWED_PATHS.contains(path);
        if (!allowedPath) {
            String authorization = req.getHeader("Authorization");
            if (StringUtils.isNotBlank(authorization)) {
                String access_token = authorization.replaceAll("bearer ", "");

                //校验缓存是否有token
                BoundValueOperations<String, Object> opts = redisTemplate.boundValueOps(CacheKey.USER_KEY + access_token);
                Object obj = opts.get();
                if (obj != null) {
                    LoginUser loginUser = JSONObject.parseObject(JSONObject.toJSONString(obj), LoginUser.class);
                    //用户为空，则不做任何操作
                    RequestHolder.add(loginUser);
                    RequestHolder.add(req);
                }

            } else {
                RequestHolder.remove();
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("过滤器销毁");
    }
}